import { AppMenuController } from '@ibiz-template/controller';
import { IBizContext } from '@ibiz-template/core';
import { AppMenuModel, AppMenuItemModel } from '@ibiz-template/model';
import { useAttachForce, useMount } from '@ibiz-template/react-util';
import { AppFuncCommand } from '@ibiz-template/runtime';
import { Menu } from 'antd';
import { useState } from 'react';

export interface AppMenuProps {
  context: IBizContext;
  model: AppMenuModel;
}

/**
 * 递归生成菜单数据，递给 antd 的 Menu 组件
 *
 * @author chitanda
 * @date 2022-07-25 10:07:28
 * @param {AppMenuItemModel[]} items
 * @return {*}  {any[]}
 */
function getMenus(items: AppMenuItemModel[]): any[] {
  return items.map(item => {
    const data: any = {
      key: item.source.id,
      label: item.label,
    };
    if (item.children) {
      data.children = getMenus(item.children);
    }
    return data;
  });
}

function findMenu(
  items: AppMenuItemModel[],
  key: string,
): AppMenuItemModel | null {
  return (
    items.find(item => {
      if (item.source.id === key) {
        return true;
      }
      if (item.children) {
        return findMenu(item.children, key);
      }
      return false;
    }) || null
  );
}

export function AppMenu({ context, model }: AppMenuProps) {
  const [c] = useState<AppMenuController>(() => {
    return new AppMenuController(model, context);
  });
  const [menus, setMenus] = useState<any[]>([]);

  useAttachForce(c);

  useMount(() => {
    c.init().then(() => {
      const items = getMenus(c.model.items);
      setMenus(items);
    });
    return () => c.destroy();
  });

  const onClick = async (e: any) => {
    const menu = findMenu(c.model.items, e.key);
    const appFunc = menu?.source.getPSAppFunc();
    await ibiz.commands.execute(AppFuncCommand.TAG, appFunc);
  };

  return (
    <div className='app-menu'>
      <Menu theme='dark' items={menus} onClick={onClick} />
    </div>
  );
}
